package com.lanou3g.bookstore.util.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 生成验证码
 * new对象,调用方法
 */
public class VerifyCode {
    private Random random = new Random();
    private int w = 240;//宽
    private int h = 80;//高
    private String code = "ABCDEFGHIJKLMNPQRSTUVWXYZ23456789洛天依";
    private String text = "";//验证码答案

    //随机生成颜色
    private Color randomColor() {
        int r = random.nextInt(255);
        int g = random.nextInt(255);
        int b = random.nextInt(255);
        return new Color(r, g, b);
    }

    private String randomString() {
        char c = code.charAt(random.nextInt(code.length()));
        return String.valueOf(c);
    }

    private Font randomFont() {
        int style = random.nextInt(3);
        int size = random.nextInt(7) + 30;
        return new Font(null, style, size);
    }

    private void drawLine(Graphics2D graphics) {
        graphics.setColor(randomColor());
        int x1 = 0;
        int y1 = random.nextInt(h);

        int x2 = 240;
        int y2 = random.nextInt(h);
        graphics.drawLine(x1, y1, x2, y2);
    }

    public String getText() {
        return text;
    }

    public BufferedImage getImage() {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        //设置背景 白色
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, w, h);
        //绘制文字
        StringBuilder builder = new StringBuilder();
        //todo 更改 i 的范围可以更改验证码的 位数
        for (int i = 0; i < 5; i++) {
            String s = randomString();
            //todo 这里要改成相应的
            float x = i * 1.0f * w / 5 + 8;
            float y = h - 30;
            Color color = randomColor();
            Font font = randomFont();
            graphics.setColor(color);
            graphics.setFont(font);
            graphics.drawString(s, x, y);
            builder.append(s);
        }
        text = builder.toString();
        //绘制干扰线,多少条
        for (int i = 0; i < random.nextInt(3) + 5; i++) {
            drawLine(graphics);
        }
        return image;
    }

    public void out(BufferedImage image, OutputStream os) {
        try {
            ImageIO.write(image, "JPEG", os);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
